package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author: atguigu
 * @create: 2023-08-30 11:41
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpointUrl}")
    private String endpointUrl;


    /**
     * 上传图片到MInIO
     *
     * @param file
     * @return 在线地址
     */
    @Override
    public String uploadImage(MultipartFile file) {
        try {
            //1.验证文件是否为图片（校验后缀MIME，文件内容 校验文件头信息）
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new RuntimeException("图片格式非法！");
            }

            //2.构建上传后文件名称 形式: /yyyy-MM-dd/文件名称.png
            String folderName = DateUtil.formatDate(new Date());
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            String extName = FilenameUtils.getExtension(file.getOriginalFilename());
            String objectName = "/" + folderName + "/" + fileName + "." + extName;

            //3.调用MinIoClient对象完车文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //4.拼接上传后文件访问地址
            return endpointUrl + "/" + bucketName + objectName;
        } catch (Exception e) {
            log.error("[商品服务]文件上传失败：{}", e);
            throw new RuntimeException(e);
        }
    }

    //public static void main(String[] args) {
    //    String extension = FilenameUtils.getExtension("1.png");
    //    System.out.println(extension);
    //}
}
